package com.ywjt.platformbusiness.market.commongoods.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.stx.xhb.xbanner.XBanner;
import com.ywjt.platformbusiness.R;
import com.ywjt.platformbusiness.base.BaseActivity;
import com.ywjt.platformbusiness.base.BaseModel;
import com.ywjt.platformbusiness.constants.UrlConstants;
import com.ywjt.platformbusiness.http.HttpRequest;
import com.ywjt.platformbusiness.http.HttpStringCallBack;
import com.ywjt.platformbusiness.market.commongoods.adapter.GoodsDetailCommentAdapter;
import com.ywjt.platformbusiness.market.commongoods.model.GoodsDetail;
import com.ywjt.platformbusiness.market.commongoods.view.BottomGoodSelectDialog;
import com.ywjt.platformbusiness.util.JsonUtils;
import com.ywjt.platformbusiness.util.ToastUtil;
import com.ywjt.platformbusiness.widget.CouponPickBottomDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.ywjt.platformbusiness.common.MethodUtils.getUserId;


public class Activity_GoodsDetail extends BaseActivity implements View.OnClickListener {

    private XBanner banner;
    private LinearLayout llBuy;
    private LinearLayout llAddCart;
    private int goodsnumn=1;
    private String goodsid="";
    private TextView tvBuyNum;
    private LinearLayout llCart;
    private LinearLayout llPickCoupon;
    private TextView tvGoodsName;
    private TextView tvPostAddress;
    private TextView tvGoodPrice;
    private WebView tvDetail;
    private TextView tvCouponTip,tvCoupon;
    private LinearLayout llcallservice;
    private RecyclerView rcCommon;
    private TextView tvMore;
    private  GoodsDetail goodsDetail;
    private GoodsDetailCommentAdapter detailCommentAdapter;
    private List<String> banners;

    private String shopId="";
    public static void actionStart(Context context,String goodsid,String shopId) {
        Intent intent = new Intent(context, Activity_GoodsDetail.class);
        intent.putExtra("goodsid",goodsid);
        intent.putExtra("shopId",shopId);
        context.startActivity(intent);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tvMore:
                ActivityCommentDetail.actionStart(this);
                break;
            case R.id.llBuy:
                //先选择规格
                //ActivitySettleMent.actionStart(this);
                BottomGoodSelectDialog goodSelectDialog1=new BottomGoodSelectDialog(Activity_GoodsDetail.this,goodsDetail);
                goodSelectDialog1.setClicklistener(new BottomGoodSelectDialog.ClickLintener() {
                    @Override
                    public void confirm(int num, String skuId, String price  ) {
                        goodSelectDialog1.dismiss();
                    }
                });
                goodSelectDialog1.show(getSupportFragmentManager());
                break;
            case R.id.llPickCoupon:
                //选择优惠券
                CouponPickBottomDialog dialog=new CouponPickBottomDialog(Activity_GoodsDetail.this,goodsDetail.getResult().getDiscountCouponList());
                dialog.show(getSupportFragmentManager());
                break;
            case R.id.llAddCart:
                //先选择规格
                BottomGoodSelectDialog goodSelectDialog=new BottomGoodSelectDialog(Activity_GoodsDetail.this,goodsDetail);
                goodSelectDialog.setClicklistener(new BottomGoodSelectDialog.ClickLintener() {
                    @Override
                    public void confirm(int num, String skuId, String price  ) {
                        goodsnumn=num;
                        addCart(skuId,price);
                        goodSelectDialog.dismiss();
                    }
                });
                goodSelectDialog.show(getSupportFragmentManager());
                break;
        }
    }

    //添加商品到购物车
    public void addCart(String skuid,String price){
        JSONObject map=new JSONObject();
        try {
            map.put("commodityId",String.valueOf(goodsid));//商品id
            map.put("commodityPrice",price);
            map.put("num",String.valueOf(goodsnumn));//数量
            map.put("supShopId",goodsDetail.getResult().getSupShopId());
            map.put("shopId",!shopId.equals("")?shopId:goodsDetail.getResult().getSupShopId());
            map.put("commoditySkuId",skuid);//库存id
        } catch (JSONException e) {
            e.printStackTrace();
        }


        new HttpRequest(getContext()).doPost(UrlConstants.  addShopCar, null, map,new HttpStringCallBack() {
            @Override
            public void onSuccess(Object result) {
                if (result instanceof BaseModel) {
                   BaseModel model=(BaseModel)result;
                   if(model.getCode()==200){
                       ToastUtil toastUtil=new ToastUtil(getContext(),R.layout.popu_success1,"添加成功，在购物车等亲~",1);
                       toastUtil.show();
                   }else {
                       ToastUtil toastUtil=new ToastUtil(getContext(),R.layout.popu_success1,model.getMessage(),2);
                       toastUtil.show();
                   }
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                Toast.makeText(getContext(),msg,Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setAndroidNativeLightStatusBar(true);
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_goodsdetail;
    }

    @Override
    protected void initView() {
        setTitleText("商品详情");
        goodsid=getIntent().getStringExtra("goodsid");
        shopId=getIntent().getStringExtra("shopId");
        llBuy=findViewById(R.id.llBuy);
        rcCommon=findViewById(R.id.rcCommon);

        llBuy.setOnClickListener(this::onClick);
        tvGoodPrice=findViewById(R.id.tvGoodPrice);
        llAddCart=findViewById(R.id.llAddCart);
        tvPostAddress=findViewById(R.id.tvPostAddress);
        tvGoodsName=findViewById(R.id.tvGoodsName);
        tvCoupon=findViewById(R.id.tvCoupon);
        tvCouponTip=findViewById(R.id.tvCouponTip);
        tvBuyNum=findViewById(R.id.tvBuyNum);
        llAddCart.setOnClickListener(this::onClick);
        banner=findViewById(R.id.banner);
        tvMore=findViewById(R.id.tvMore);
        tvDetail=findViewById(R.id.tvDetail);
        llPickCoupon=findViewById(R.id.llPickCoupon);
        llCart=findViewById(R.id.llCart);
        llCart.setOnClickListener(this::onClick);
        tvMore.setOnClickListener(this::onClick);
        llPickCoupon.setOnClickListener(this::onClick);
        llcallservice=findViewById(R.id.llcallservice);
        llcallservice.setOnClickListener(this::onClick);

//        detailCommentAdapter=new GoodsDetailCommentAdapter(data);
//        rcCommon.setAdapter(detailCommentAdapter);
//        rcCommon.setLayoutManager(new LinearLayoutManager(this));


        getData();
    }

    //获取商品详情
    public void getData(){
        new HttpRequest(getContext()).doGet(UrlConstants.getCommodityDetail+goodsid,null, new HttpStringCallBack() {
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    int code = jsonObject.getInt("code");
                    if (code == 200) {
                        Object obj = JsonUtils.fromJson(result.toString(), GoodsDetail.class);
                        if (obj instanceof GoodsDetail) {
                            goodsDetail = (GoodsDetail) obj;
                            setView();
                           setBanner();
                        }
                    }else {
                        Toast.makeText(getContext(),message,Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                Toast.makeText(getContext(),msg,Toast.LENGTH_SHORT).show();
            }
        });
    }

    //设置数据
    public void setView(){
        tvGoodsName.setText(goodsDetail.getResult().getName());
        tvGoodPrice.setText("￥"+goodsDetail.getResult().getPrice());
        tvBuyNum.setText(goodsDetail.getResult().getSalesVolume()+"已购买");
        tvPostAddress.setText(goodsDetail.getResult().getAddress());

        if (goodsDetail.getResult().getDiscountCouponList()!=null&&goodsDetail.getResult().getDiscountCouponList().size()>0){
            tvCouponTip.setText("领券");
            tvCoupon.setText("满"+goodsDetail.getResult().getDiscountCouponList().get(0).getReachAmount()+"元减"+
                    goodsDetail.getResult().getDiscountCouponList().get(0).getDiscountAmount()+"元");
        }else {
            tvCoupon.setVisibility(View.INVISIBLE);
            tvCouponTip.setText("暂无可用优惠券");
        }
        StringBuilder sb = new StringBuilder();
        sb.append(getHtmlData(goodsDetail.getResult().getDetailPhoto()));
        tvDetail.loadDataWithBaseURL(null,sb.toString(),"text/html", "utf-8", null);
    }

    /**
     * 富文本适配
     */
    private String getHtmlData(String bodyHTML) {
        String head = "<head>"
                + "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> "
                + "<style>img{max-width: 100%; width:auto; height:auto;}</style>"
                + "</head>";
        return "<html>" + head + "<body>" + bodyHTML + "</body></html>";
    }

    @Override
    protected void initData() {

    }

    @Override
    protected int getTitleBarType() {
        return 0;
    }

    /**banner*/
    private void setBanner() {
        String ban []=goodsDetail.getResult().getDetailPhoto().split(",");
        if (ban.length>0){
            banners=new ArrayList<>();
            for (int i=0;i<ban.length;i++){
                banners.add(ban[i]);
            }
        }
        banner.setData(banners,null);
        //加载广告图片
        banner.loadImage(new XBanner.XBannerAdapter() {
            @Override
            public void loadBanner(XBanner banner, Object object, View view, int position) {
                //在此处使用图片加载框架加载图片，demo中使用glide加载，可替换成自己项目中的图片加载框架
                Glide.with(getApplicationContext()).load(banners.get(position)).
                        placeholder(R.mipmap.icon_goodsdetail_banner)
                        .apply(new RequestOptions().transforms(new CenterCrop(), new RoundedCorners(10)))
                        .into((ImageView) view);
            }
        });
    }

}
